package com.mall.common.service.impl;

import java.sql.Timestamp;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.mall.common.dao.S_userDao;
import com.mall.common.domain.manage.S_userDomain;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.S_userService;

/**
 * Service实现类 - 管理员
 */

@Service
@Transactional(readOnly=true)
public class S_userServiceImpl extends BaseServiceImpl<S_userDomain, Long> implements S_userService {

	@Resource
	public void setBaseDao(S_userDao s_userDao) {
		super.setBaseDao(s_userDao);
	}
	
	public S_userDomain loadLoginAdmin(Long userId) {
		return find(userId);
	}
	
	public boolean isExistByUsername(String username) {
		String hql = "from S_userDomain user where lower(user.username) = lower(:username)";
		Finder f = Finder.create(hql);
		f.setParam("username", username);
		S_userDomain admin = (S_userDomain)f.findUniqueByHQL();
		if (admin != null) {
			return true;
		} else {
			return false;
		}
	}
	
	public S_userDomain getAdminByUsername(String username) {
		String hql = "from S_userDomain user where lower(user.username) = lower(:username)";
		Finder f = Finder.create(hql);
		f.setParam("username", username);
		return (S_userDomain)f.findUniqueByHQL();
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void updateLoginInfo(Long userId, String ip) {
		Date now = new Timestamp(System.currentTimeMillis());
		S_userDomain user = this.find(userId);
		if (user != null) {
			user.setLoginCount(user.getLoginCount() + 1);
			user.setLastLoginIp(ip);
			user.setLastLoginTime(now);
		}
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void remove(Long[] ids) {
		Assert.notNull(ids, "未获得操作的对象!");
		for(int i=0; i<ids.length; i++){
			S_userDomain s_user = this.find(ids[i]);
			super.remove(s_user);
		}
	}

	@Override
	public S_userDomain findByUsername(String username) {
		String hql = "from S_userDomain user where lower(user.username) = lower(:username)";
		Finder f = Finder.create(hql);
		f.setParam("username", username);
		return (S_userDomain)f.findUniqueByHQL();
	}
}